package com.whiteape.book.ui.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;

import com.gyf.immersionbar.ImmersionBar;
import com.hwangjr.rxbus.RxBus;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.whiteape.book.R;
import com.whiteape.book.common.RxEvent;
import com.whiteape.book.common.WaConstants;
import com.whiteape.book.core.manager.SiteSourceManager;
import com.whiteape.book.model.type.LoadFileType;
import com.whiteape.book.model.type.WebviewDocType;
import com.whiteape.book.ui.activity.FileSystemActivity;
import com.whiteape.book.ui.activity.QrCodeActivity;
import com.whiteape.book.ui.activity.WebviewActivity;
import com.whiteape.book.ui.base.BaseContract;
import com.whiteape.book.ui.base.BaseMVPFragment;
import com.whiteape.book.utils.ClipboardUtils;
import com.whiteape.book.utils.JumpPermissionManagement;
import com.whiteape.book.utils.LogUtils;
import com.whiteape.book.utils.RxUtils;
import com.whiteape.book.utils.SoftKeyboardUtil;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.utils.ToastUtils;
import com.whiteape.book.widget.RefreshLayout;

import java.io.File;
import java.lang.reflect.Method;
import java.util.List;

import butterknife.BindView;

import static android.app.Activity.RESULT_OK;

public class SiteSourceFragment extends BaseMVPFragment {

    private static final int OP_TYPE_QR_CODE = 0;
    private static final int OP_TYPE_LOCAL_FILE = 1;
    private static final int REQUEST_CODE_QR = 1234;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.refresh_layout_loading_outer)
    RefreshLayout refreshLayout;
    @BindView(R.id.search_view)
    SearchView searchView;

    SiteSourceContentFragment childFragment;

    @Override
    protected BaseContract.BasePresenter bindPresenter() {
        return null;
    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {
        refreshLayout.showFinish();

    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        SoftKeyboardUtil.hideKeyboard(searchView);
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
        setHasOptionsMenu(true);
//        toolbar.inflateMenu(R.menu.menu_web_source);

        ImmersionBar.with(this)
                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
                .statusBarDarkFont(true)
                .statusBarColor(R.color.colorPrimary)
                .init();
        refreshLayout.showFinish();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (searchView != null) {
            searchView.clearFocus();
            SoftKeyboardUtil.hideKeyboard(searchView);
        }
    }


    @Override
    protected void initEvent() {
        super.initEvent();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                return refreshDataSet(query);
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return refreshDataSet(newText);
            }
        });
//        refreshLayout.dispatchT

    }

    private boolean refreshDataSet(String keyword) {
//        if (StringUtils.isEmpty(keyword)) {
//            return false;
//        }
        if (childFragment != null) {
            childFragment.filterByWord(keyword);
            return true;
        }
        return false;

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        LogUtils.d("onCreateOptionsMenu");
        menu.clear();
        inflater.inflate(R.menu.menu_web_source, menu);
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        childFragment = new SiteSourceContentFragment();
        getChildFragmentManager().beginTransaction().add(R.id.ll_web_source_content, childFragment).commit();
    }


    private void importSiteSourceByClipboard() {
        if (getContext() != null) {
            String txt = ("" + ClipboardUtils.getText(getContext()));
            txt = StringUtils.trim(txt);
            addDisposable(SiteSourceManager.getInstance().importSiteSource(txt)
                    .compose(RxUtils::toSimpleSingle)
                    .subscribe(integer -> {
                        showDialogImportOk(getContext(), integer);

                    }, throwable -> {
                        showDialogImportFailed(getContext());

                    }));
        }

    }

    private void importSiteSourceByUrl() {
        if (getContext() != null) {
            EditText editText = new EditText(getContext());
            new AlertDialog.Builder(getContext())
                    .setTitle(R.string.add_source_by_url_title)
                    .setView(editText)
                    .setPositiveButton(R.string.wa_common_sure, ((dialogInterface, i) -> {
                        String url = editText.getText().toString().trim();
                        //全角空格
//                        url = url.replaceAll((char)12288+"","");
                        url = StringUtils.trim(url);
                        if (!StringUtils.isUrlFormat(url)) {
                            showUrlError(getContext());
                            dialogInterface.dismiss();
                            return;
                        }
                        addDisposable(SiteSourceManager.getInstance()
                                .importSiteSourceByUrl(url)
                                .compose(RxUtils::toSimpleSingle)
                                .subscribe(integer -> showDialogImportOk(getContext(), integer),
                                        throwable -> showDialogImportFailed(getContext())));

                    }))
                    .setNegativeButton(R.string.wa_common_cancel, (((dialogInterface, i) -> {
                        dialogInterface.dismiss();
                    }))).create().show();

        }

    }

    private void startQrCodeActivity() {

        Intent intent = new Intent(getContext(), QrCodeActivity.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, REQUEST_CODE_QR);
    }

    private void startFileSystemActivity() {
        Intent intent = new Intent(getContext(), FileSystemActivity.class);
        intent.putExtra(FileSystemActivity.FILE_TYPE_KEY, LoadFileType.FILE_TYPE_SITE_SOURCE);
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, LoadFileType.FILE_TYPE_SITE_SOURCE);
    }

    private void importSiteSourceBy(int type) {
        RxPermissions rxPermissions = new RxPermissions(this);
        if (type == OP_TYPE_LOCAL_FILE && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            startFileSystemActivity();
            return;
        } else if (type == OP_TYPE_QR_CODE && rxPermissions.isGranted(Manifest.permission.CAMERA)) {
            startQrCodeActivity();
            return;
        } else {
            new AlertDialog.Builder(getContext())
                    .setTitle(R.string.wa_common_tip)
                    .setMessage(R.string.permission_request_sdcard)
                    .setPositiveButton(R.string.wa_common_sure, ((dialogInterface, i) -> {
                        dialogInterface.dismiss();
                        rxPermissionRequest(rxPermissions, type);
                    }))
                    .setNegativeButton(R.string.wa_common_cancel, ((dialogInterface, i) -> {
                        dialogInterface.dismiss();
                        ToastUtils.show("已经拒绝权限，需要重新打开授权才可以导入本地网源哦");
                    })).show();
        }

    }

    private void rxPermissionRequest(RxPermissions rxPermissions, int type) {
        String permissionRequired = type == OP_TYPE_LOCAL_FILE ? Manifest.permission.WRITE_EXTERNAL_STORAGE
                : Manifest.permission.CAMERA;
        addDisposable(rxPermissions.requestEach(permissionRequired)
                .subscribe(permission -> {
                    if (permission.granted) {
                        // `permission.name` is granted !
                        if (type == OP_TYPE_LOCAL_FILE) {
                            startFileSystemActivity();
                        } else if (type == OP_TYPE_QR_CODE) {
                            startQrCodeActivity();
                        }

                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // Denied permission without ask never again
                        if (getContext() == null) {
                            ToastUtils.show("必须授权才能下一步操作哦");
                            return;
                        }
                        importSiteSourceBy(type);
                    } else {
                        // Denied permission with ask never again
                        // Need to go to the settings
                        if (getContext() == null) {
                            ToastUtils.show("已经拒绝权限，需要去系统设置打开权限哦");
                            return;
                        }
                        new AlertDialog.Builder(getContext())
                                .setTitle(R.string.wa_common_tip)
                                .setMessage(R.string.permission_request_sdcard_goto_setting)
                                .setPositiveButton(R.string.wa_common_sure, ((dialogInterface, i) -> {
                                    //goto setting
                                    dialogInterface.dismiss();
                                    JumpPermissionManagement.goToSetting(getActivity());

                                }))
                                .setNegativeButton(R.string.wa_common_cancel, ((dialogInterface, i) -> {
                                    dialogInterface.dismiss();
                                    ToastUtils.show("已拒绝权限，无法导入本地网源");
                                })).show();

                    }
                }));

    }


    private void showDialogImportOk(Context context, int successCount) {
        RxBus.get().post(RxEvent.SITE_SOURCE_ADDED, "");

        if (childFragment != null) {
            childFragment.finishRefresh(SiteSourceManager.getInstance().getSiteSourceAll());
        }
        refreshLayout.showFinish();

        new AlertDialog.Builder(context)
                .setTitle(R.string.wa_common_tip)
                .setMessage("成功导入" + successCount + "个网源")
                .setPositiveButton(R.string.wa_common_sure, (((dialogInterface, i) -> {
                    dialogInterface.dismiss();
                }))).show();
    }

    private void showDialogImportFailed(Context context) {
        refreshLayout.showFinish();
        new AlertDialog.Builder(context)
                .setTitle(R.string.wa_common_tip)
                .setMessage("导入失败，请检查格式是否准确")
                .setPositiveButton(R.string.wa_common_sure, (((dialogInterface, i) -> {
                }))).show();
    }

    private void showUrlError(Context context) {
        refreshLayout.showFinish();
        new AlertDialog.Builder(context)
                .setTitle(R.string.wa_common_tip)
                .setMessage("格式错误，请确认是http开头的链接")
                .setPositiveButton(R.string.wa_common_sure, (((dialogInterface, i) -> {
                }))).show();
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.action_add_by_clipboard:
                importSiteSourceByClipboard();
                break;
            case R.id.action_add_by_file:
                importSiteSourceBy(OP_TYPE_LOCAL_FILE);
                break;
            case R.id.action_add_by_url:
                importSiteSourceByUrl();
                break;
            case R.id.action_add_by_qr_code:
                importSiteSourceBy(OP_TYPE_QR_CODE);
                break;
            case R.id.action_how_to_import:
//                openUrl(WaConstants.URL_HOW_TO_IMPORT_SOURCE);

                startActivity(new Intent(getContext(), WebviewActivity.class).putExtra(WebviewActivity.KEY_WEBVIEW_TYPE, WebviewDocType.WEBVIEW_DOC_TYPE_QA));
                break;
            case R.id.action_how_to_create:
                openUrl(WaConstants.URL_HOW_TO_CREATE_SOURCE);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void openUrl(String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }
    @Override
    protected int getContentId() {
        return R.layout.fragment_site_source;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            LogUtils.e("SiteSourceFragment onActivityResult ,resultCode not ok, is " + resultCode);
            return;
        }
        if (requestCode == REQUEST_CODE_QR) {
            if (data == null) {
                return;
            }
            refreshLayout.showLoading();
            addDisposable(SiteSourceManager.getInstance()
                    .importSiteSource(data.getStringExtra("result"))
                    .compose(RxUtils::toSimpleSingle)
                    .subscribe(integer -> showDialogImportOk(getContext(), integer),
                            throwable -> showDialogImportFailed(getContext())));
        } else if (requestCode == LoadFileType.FILE_TYPE_SITE_SOURCE) {

            List<File> fileList = (List<File>) data.getSerializableExtra("data");
            addDisposable(SiteSourceManager.getInstance().importSiteSource(fileList)
                    .compose(RxUtils::toSimpleSingle)
                    .subscribe(integer -> showDialogImportOk(getContext(), integer),
                            throwable -> showDialogImportFailed(getContext())));


        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (childFragment.onKeyDown(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
